extern crate libc;

use std::fs::File;
use std::os::unix::io::{AsRawFd, RawFd};
use std::{io, ptr};
use std::ffi::c_void;
use super::raw::Raw;

#[derive(Debug)]
pub struct Mmap {
    ptr: *mut libc::c_void,
    len: usize,
}

impl Mmap {
    /// This is a thin wrapper around the `mmap` sytem call.
    fn new(
        start : *mut libc::c_void,
        len: usize,
        prot: libc::c_int,
        flags: libc::c_int,
        file: RawFd,
        offset: u64,
    ) -> io::Result<Mmap> {
        let alignment = offset % page_size() as u64;
        let aligned_offset = offset - alignment;
        let aligned_len = len + alignment as usize;
        if aligned_len == 0 {
            // Normally the OS would catch this, but it segfaults under QEMU.
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "memory map must have a non-zero length",
            ));
        }

        unsafe {
            let ptr = libc::mmap(
                start,
                aligned_len as libc::size_t,
                prot,
                flags,
                file,
                aligned_offset as libc::off_t,
            );

            if ptr == libc::MAP_FAILED {
                Err(io::Error::last_os_error())
            } else {
                Ok(Mmap {
                    ptr: ptr.offset(alignment as isize),
                    len: len,
                })
            }
        }
    }

    pub fn map_with_start(start: *mut libc::c_void,len: usize, file: &File, offset: u64) -> io::Result<Mmap> {
        Mmap::new(
            start,
            len,
            libc::PROT_READ | libc::PROT_WRITE,
            libc::MAP_SHARED,
            file.as_raw_fd(),
            offset,
        )
    }

    pub fn map_mut(len: usize, file: &File, offset: u64) -> io::Result<Mmap> {
        Mmap::new(
            ptr::null_mut(),
            len,
            libc::PROT_READ | libc::PROT_WRITE,
            libc::MAP_SHARED,
            file.as_raw_fd(),
            offset,
        )
    }

    pub fn to_raw(&self) -> Raw {
        Raw{h:Some(self.ptr() as *const c_void)}
    }

    #[inline]
    pub fn ptr(&self) -> *const u8 {
        self.ptr as *const u8
    }
    
    #[inline]
    pub fn usize(&self) -> usize {
        self.ptr as usize
    }
    
    #[inline]
    pub fn mut_ptr(&mut self) -> *mut u8 {
        self.ptr as *mut u8
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.len
    }
}
impl Drop for Mmap {
    fn drop(&mut self) {
        let alignment = self.ptr as usize % page_size();
        unsafe {
            assert!(
                libc::munmap(
                    self.ptr.offset(-(alignment as isize)),
                    (self.len + alignment) as libc::size_t
                ) == 0,
                "unable to unmap mmap: {}",
                io::Error::last_os_error()
            );
        }
    }
}

fn page_size() -> usize {
    unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize }
}
